package cn.itcast.service;

import cn.itcast.entity.PageResult;
import cn.itcast.entity.QueryPageBean;
import cn.itcast.mapper.CheckItemMapper;
import cn.itcast.mapper.UserMapper;
import cn.itcast.pojo.CheckItem;
import com.alibaba.dubbo.config.annotation.Service;
import com.github.pagehelper.Page;
import com.github.pagehelper.PageHelper;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.slf4j.impl.Log4jLoggerFactory;
import org.springframework.beans.factory.annotation.Autowired;

import java.util.List;


@Service
public class CheckItemServiceImpl implements CheckItemService {


    private Logger logger = LoggerFactory.getLogger(CheckItemServiceImpl.class);

    @Autowired
    private CheckItemMapper checkItemMapper;


    /**
     * 新建检查项
     * @param checkItem
     */
    @Override
    public void add(CheckItem checkItem) {
        checkItemMapper.add(checkItem);
    }

    /**
     * 分页查询
     * @param queryPageBean
     * @return
     */
    @Override
    public PageResult findPage(QueryPageBean queryPageBean) {
        Integer currentPage = queryPageBean.getCurrentPage();
        Integer pageSize = queryPageBean.getPageSize();
        String queryString = queryPageBean.getQueryString();
        //完成分页查询，使用mybatis提供的分页助手插件
        PageHelper.startPage(currentPage,pageSize);
        //获取page类型
        Page<CheckItem> page = checkItemMapper.findPage(queryString);
        //获取总记录数
        long total = page.getTotal();
        //获取CheckItem集合
        List<CheckItem> rows = page.getResult();
        //返回PageResult对象
        return new PageResult(total,rows);
    }

    /**
     * 根据id删除检查项
     * @param id
     */
    @Override
    public void delete(Integer id) {
        //判断是否已经关联到检查组
        Long count = checkItemMapper.findCountByCheckItemId(id);
        if (count == 0){
            checkItemMapper.delete(id);
        }else {
            logger.error("check item id:{} rel is not null", id);
            throw new RuntimeException("当前检查项被引用，不能删除");
        }
    }

    /**
     * 根据id检查单条数据进行回显
     * @param id
     */
    @Override
    public CheckItem findById(Integer id) {
        CheckItem checkItem = checkItemMapper.findById(id);
        return checkItem;
    }

    /**
     * 更新数据
     * @param checkItem
     */
    @Override
    public void edit(CheckItem checkItem) {
        checkItemMapper.edit(checkItem);
    }

    @Override
    public List<CheckItem> findAll() {
        return checkItemMapper.findAll();
    }
}
